<template>
  <div class="agent-apply">
    <cell-group>
      <field v-model="agentInfo.name" label-width="100px" readonly label="邀请代理：" placeholder="米粉" />
      <!-- // 如果是母公司二维码时 id = 1 或者 没有手机号 -->
      <field
        v-if="!(!agentInfo.phone) || agentInfo.id != 1"
        v-model="agentInfo.phone"
        label-width="100px"
        readonly
        label="联系电话："
        placeholder="联系电话"
      />
      <field
        v-if="!(!agentInfo.phone) || agentInfo.id != 1"
        v-model="agentInfo.provinceName +'-' + agentInfo.cityName +'-' + agentInfo.countryName+'-' + agentInfo.address"
        label-width="100px"
        readonly
        label="联系地址："
        placeholder="联系地址"
      />
      <div class="line">填写内容</div>
      <!-- <field v-model="nowLevel" label-width="100px" readonly label="现在等级：" placeholder="米粉" /> -->
      <!-- @click="popupType = 'grade', showPopup = true"  -->
      <field v-model="selectedAgencyLevel.level_name" label-width="100px" label="代理等级：" readonly />
      <field v-model="applyInfo.name" label-width="100px" label="姓名：" placeholder="请输入你的姓名" />
      <field
        v-model="applyInfo.phone"
        label-width="100px"
        label="手机号："
        placeholder="请输入你的手机号"
        type="tel"
      />

      <field
        v-model="applyInfo.smsCode"
        label-width="100px"
        label="验证码："
        placeholder="请输入验证码"
        type="number"
      >
        <van-button
          slot="button"
          size="small"
          label-width="100px"
          type="primary"
          @click="sendSMS(applyInfo.phone)"
        >{{sendsms ? "已发送"+sendsmstext+"秒" : sendsmstext}}</van-button>
      </field>
      <field
        v-model="applyInfo.password"
        label-width="100px"
        type="password"
        label="密码："
        placeholder="请输入密码"
      />
      <field
        v-model="applyInfo.repassword"
        label-width="100px"
        type="password"
        label="密码确认："
        placeholder="请再次输入密码"
      />
      <field v-model="applyInfo.wxNumber" label-width="100px" label="微信号：" placeholder="请输入你的微信号" />
      <field
        v-model="applyInfo.idCard"
        label-width="100px"
        label="身份证号："
        placeholder="请输入你的身份证号"
        type="string"
      />
      <field
        @click="popupType = 'city', showPopup = true"
        v-model="area"
        label-width="100px"
        label="地区："
        placeholder="请选择你的地区"
        readonly
        right-icon="arrow-down"
      />
      <field v-model="applyInfo.address" label-width="100px" label="详细地址：" placeholder="请输入你的详细地址" />
      <field v-model="applyInfo.remark" label-width="100px" label="备注：" placeholder="请输入备注" />

      <field
        v-model="agentInfo.needMoney"
        label-width="100px"
        label="打款金额："
        placeholder="请输入金额"
        type="number"
        readonly
      />
      <field
        v-model="selectedDate"
        @click="popupType = 'date', showPopup = true"
        label-width="100px"
        label="打款日期："
        placeholder="请选择打款日期"
        readonly
        right-icon="arrow-down"
      />
      <field
        @click="popupType = 'payType', showPopup = true"
        v-model="selectedPayType.name"
        label-width="100px"
        label="打款方式："
        readonly
        right-icon="arrow-down"
      />
      <field
        v-if="selectedPayType.id == 1"
        v-model="applyInfo.account"
        label-width="100px"
        label="支付宝账号："
        placeholder="请输入你的支付宝账号"
      />

      <field
        v-if="selectedPayType.id == 2"
        v-model="applyInfo.account"
        label-width="100px"
        label="银行卡账号："
        placeholder="请输入你的银行卡账号"
      />

      <field
        v-if="selectedPayType.id == 2"
        v-model="applyInfo.bankName"
        label-width="100px"
        label="银行名称："
        placeholder="请输入银行名称"
      />

      <!-- <field v-if="selectedPayType.id == 2"
        v-model="applyInfo.branchName"
        label-width="100px"
        label="开户银行："
        placeholder="请输入你的银行支行名称"
      />-->

      <!-- <field v-if="selectedPayType.id == 1"
        v-model="applyInfo.accountName"
        label-width="100px"
        label="支付宝实名："
        placeholder="请输入你的支付宝实名"
      />-->

      <field
        v-if="selectedPayType.id == 2"
        v-model="applyInfo.accountName"
        label-width="100px"
        label="开户实名："
        placeholder="请输入你的开户实名"
      />

      <div class="upload-proof">
        <div class="upload-proof-text">
          头像
          <br />(1张)：
        </div>
        <uploader
          :max-count="1"
          v-model="headList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
      <div class="upload-proof">
        <div class="upload-proof-text">
          打款凭证
          <br />(1-3张)：
        </div>
        <uploader
          :max-count="3"
          v-model="moneyList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
      <div class="upload-proof">
        <div class="upload-proof-text">
          手持证
          <br />(1张)：
        </div>
        <uploader
          :max-count="1"
          v-model="idcardList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
    </cell-group>

    <pay-info :type="selectedPayType.id"></pay-info>

    <div class="submit">
      <van-button
        :type="'info'"
        size="large"
        :loading="isSubmitting"
        :loading-text="'正在提交'"
        :disabled="isSubmitting"
        @click="goToApply"
      >{{isSubmitting ? '正在提交' : '确认申请'}}</van-button>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'grade'">
        <picker
          @cancel="onCancel"
          value-key="level_name"
          show-toolbar
          :columns="agencyLevelList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'payType'">
        <picker
          @cancel="onCancel"
          value-key="name"
          show-toolbar
          :columns="payTypeList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'date'">
        <datetime-picker
          v-model="currentDate"
          type="date"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="onConfirm"
          @cancel="onCancel"
        />
      </div>
      <div v-if="popupType == 'city'">
        <van-area :area-list="areaList" value="110101" @confirm="onConfirm" @cancel="onCancel" />
      </div>
    </popup>
  </div>
</template>

<script>
import {
  Field,
  Cell,
  CellGroup,
  Uploader,
  Button,
  Picker,
  Area,
  DatetimePicker,
  Toast
} from "vant";
import payInfo from "../components/pay_info.vue";
import popup from "../components/popup.vue";
var moment = require("moment");
const md5 = require("js-md5");
import areaList from "../service/area.js";
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
import sendSMS from "../mixins/send_sms.js";
import _ from "lodash";
import {
  getImageMetaInfo,
  getImageAfterCompressFromCanvas,
  getImageAfterCompressFromImgzip,
  getImageAfterCompressBatch
} from "../service/imageCompress.js";
import imgMaxSize from "../mixins/img_maxsize.js";

export default {
  components: {
    Field,
    Cell,
    CellGroup,
    Uploader,
    vanButton: Button,
    payInfo,
    popup,
    Picker,
    vanArea: Area,
    DatetimePicker,
    Toast
  },
  mixins: [sendSMS, imgMaxSize],
  data() {
    return {
      area: "",
      selectedArea: [
        // { code: "110000", name: "北京市" },
        // { code: "110100", name: "北京市" },
        // { code: "110101", name: "东城区" }
      ],
      areaList: areaList,
      selectedDate: "",
      currentDate: new Date(),
      maxDate: new Date(),
      showPopup: false,
      popupType: "grade",
      codeId: this.$route.query.codeId,
      // levelName: this.$route.query.levelName,
      agentInfo: {},
      applyInfo: {
        codeId: this.$route.query.codeId,
        agentSuper: "", // 上级ID
        agentLevel: "", // 代理级别
        smsCode: "", // 验证码
        name: "", // 姓名
        phone: "", // 电话
        password: "", // 密码
        repassword: "", // 重复密码
        wxNumber: "", // 微信号
        idCard: "", // 身份证
        provinceCode: "", // 省份code
        cityCode: "", // 城市code
        countryCode: "", // 区县code
        address: "", // 详细地址
        remark: "", // 备注
        payType: "", // 打款类型
        payMoney: "", // 打款金额
        payTime: "", // 打款日期
        signTime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"), // 签约时间
        account: "", // 账户
        branchName: "", // 开户行
        accountName: "", // 账户名
        headImg: "", // 头像
        payImage: "", // 打款凭证
        handDocuments: "" // 手持证件
      },
      agencyLevelList: [
        {
          id: 0,
          level_name: "全部"
        }
      ],
      selectedAgencyLevel: {
        // id: 0,
        // level_name: "全部"
      },
      selectedPayType: {
        id: 1,
        name: "支付宝"
      },
      payTypeList: [
        {
          id: 1,
          name: "支付宝"
        },
        {
          id: 2,
          name: "银行转账"
        }
      ],
      value: "",
      // nowLevel: "",
      // upgradeLevel: '',
      headList: [],
      moneyList: [],
      idcardList: [],
      time: moment(new Date()).format("YYYY年MM月DD日"),
      isSubmitting: false
    };
  },
  computed: {
    ...mapState({
      userinfo: state => state.login_module.userinfo,
      countAlias: "userinfo"
    })
  },
  async mounted() {
    this.sendType = "agentApply";

    // 获取邀请代理信息
    await this.getAgentInfo();

    // 获取代理等级列表
    await this.getAgencyLevel();

    // 筛选显示代理
    this.agencyLevelList.forEach(item => {
      if (item.id == this.agentInfo.levelId) {
        this.selectedAgencyLevel = item;
      }
    });

    if (JSON.stringify(this.selectedAgencyLevel) === "{}") {
      this.$router.replace({
        path: "/login"
      });
    }

    // 设置支付方式默认值
    this.selectedPayType = this.payTypeList[0];
  },
  methods: {
    // oversize() {
    //   let size = this.imgMaxSize / 1024 / 1024;
    //   Toast(`图片大小不能超过` + size + "Mb");
    // },
    // 申请代理
    async goToApply() {
      // console.log(this.headList[0])
      let payImage = [...this.moneyList].map(item => item.content);

      this.applyInfo = Object.assign({}, this.applyInfo, {
        agentSuper: Number(this.agentInfo.id), // 上级ID
        agentLevel: Number(this.selectedAgencyLevel.id), // 代理级别
        password: this.applyInfo.password,
        provinceCode:
          this.selectedArea.length != 0 ? this.selectedArea[0].code : "", // 省份code
        cityCode:
          this.selectedArea.length != 0 ? this.selectedArea[1].code : "", // 城市code
        countryCode:
          this.selectedArea.length != 0 ? this.selectedArea[2].code : "", // 区县code
        payType:
          this.selectedPayType.length != 0
            ? Number(this.selectedPayType.id)
            : "",
        payMoney: Number(Number(this.agentInfo.needMoney).toFixed(2)),
        // moment(this.time).format("YYYY-MM-DD")
        payTime: this.time ? moment(this.time).format("YYYY-MM-DD") : "",
        headImg: this.headList.length != 0 ? this.headList[0].content : "",
        payImage: this.moneyList.length != 0 ? payImage : "",
        handDocuments:
          this.idcardList.length != 0 ? this.idcardList[0].content : "",
        applyType: 1,
        type: this.sendType
      });

      let verify = {
        name: "姓名",
        phone: "联系电话",
        smsCode: "验证码",
        password: "密码",
        wxNumber: "微信",
        idCard: "身份证",
        provinceCode: "地区",
        cityCode: "地区",
        countryCode: "地区",
        address: "详细地址",
        payMoney: "打款金额",
        payTime: "打款日期",
        account: "账号",
        // accountName: "账户名", // 账户名
        headImg: "头像",
        payImage: "打款凭证",
        handDocuments: "手持证"
      };

      // 银行卡 支付时
      if (this.selectedPayType.id == 2) {
        this.applyInfo = Object.assign({}, this.applyInfo, {
          bankName: this.applyInfo.bankName,
          accountName: this.applyInfo.accountName
        });

        verify = Object.assign({}, verify, {
          bankName: "银行名称",
          accountName: "开户实名"
          // branchName: "开户行",
        });
      }

      for (let item in this.applyInfo) {
        if (!this.applyInfo[item]) {
          if (item in verify) {
            // console.log(item);
            Toast(verify[item] + "不能为空");
            return false;
          }
        }
      }

      if (this.applyInfo.password != this.applyInfo.repassword) {
        Toast("两次密码输入不相同");
        return false;
      }

      // this.applyInfo.repassword = '';
      // this.applyInfo.password = '';

      let submitData = _.cloneDeep(this.applyInfo);

      submitData.password = md5(submitData.password);
      delete submitData.repassword;

      // 压缩图片
      let payImages = await getImageAfterCompressBatch(submitData.payImage);
      // console.log(payImages);
      let headImgs = await getImageAfterCompressBatch([submitData.headImg]);
      let handDocuments = await getImageAfterCompressBatch(
        [submitData.handDocuments]
      );
      submitData.payImage = payImages;
      submitData.headImg = headImgs[0];
      submitData.handDocuments = handDocuments[0];

      // console.log("最终数据：", submitData);
      // return false;

      if (this.isSubmitting) {
        Toast("正在提交，请稍等");
        return false;
      }

      // Toast('正在提交，请稍等')
      this.isSubmitting = true;
      http.post(urls.TJDLSQ, submitData).then(res => {
        console.log(res);
        this.isSubmitting = false;
        if (res.data.code == 200) {
          Toast.success("提交申请成功");

          setTimeout(() => {
            this.$router.replace({
              path: "/login"
            });
          }, 1000);
        } else {
          Toast(res.data.msg);
        }
      });
    },
    // 获取代理等级列表
    getAgencyLevel() {
      // console.log(this.userinfo)
      return new Promise((resolve, reject) => {
        http
          .post(urls.JZDLXLK, {
            // id: this.userinfo.id,
            // tokenid: this.userinfo.id
          })
          .then(res => {
            if (res.data.code == 200) {
              this.agencyLevelList = res.data.data;
              resolve();
            }
          });
      });
    },

    // 获取上级信息
    getAgentInfo() {
      return new Promise((resolve, reject) => {
        http
          .post(urls.HQSJXX, {
            codeId: this.codeId
          })
          .then(res => {
            // console.log(res);
            if (res.data.code == 200) {
              this.agentInfo = res.data.data;
              console.log("id:", this.agentInfo.id);
              resolve();
            }
          });
      });
    },
    afterRead(file) {
      // console.log(file);
      // this.filesList.push({url: file.content})
    },

    // 时间格式化
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    onCancel() {
      this.showPopup = false;
    },

    // popup确定时，根据popupType做不同处理
    onConfirm(value) {
      if (this.popupType == "payType") {
        this.selectedPayType = value;
        // this.payType = this.selectedPayType
      } else if (this.popupType == "grade") {
        this.selectedAgencyLevel = value;
      } else if (this.popupType == "city") {
        this.selectedArea = value;
        this.area =
          this.selectedArea[0].name +
          "-" +
          this.selectedArea[1].name +
          "-" +
          this.selectedArea[2].name;
      } else if (this.popupType == "date") {
        this.selectedDate = moment(value).format("YYYY年MM月DD日");
        this.time = value;
      }
      this.showPopup = false;
      // this.pageNumber = 1
      // this.allList = []

      // this.loading = false
      // this.finished = false
    }
  }
};
</script>

<style scoped>
.upload-proof {
  padding: 10px 15px;
  display: flex;
}

.upload-proof-text {
  width: 100px;
  /* padding-right: 10px; */
  color: #323233;
  text-align: left;
}

.submit {
  margin-bottom: 30px;
}

.line {
  padding: 10px 15px;
  background-color: #f9f9f9;
}
</style>